import React, { Component } from 'react';
import MyNavBar from "../../components/MyNavBar"
import { getCurrentCity, setLocalCity } from '../../utils/city'
import styles from './index.module.scss'
import { AutoSizer, List } from 'react-virtualized'
const TITLE_HEIGHT = 36
const CITY_HEIGHT = 50
class City extends Component {
    constructor() {
        super()
        this.state = {
            cityObj: null,
            cityIndexList: null,
            selectIndex: 0, // 右边选中的索引
        }
    }

    // 给List添加ref
    listRef = React.createRef();
    componentWillMount() {
        this.getCityList()
    }
    /* 
    * 获取城市列表数据
    */
    getCityList = async () => {
        const res = await this.axios.get("/area/city?level=1")
        console.log(res);
        // 左边数据处理
        const tempObj = {}
        res.data.body.forEach((item) => {
            // 截取首字母
            const firstLetter = item.short.substring(0, 1)
            console.log(firstLetter);
            // 判断之前知否存在 如果存在就添加 不存在就赋值
            if (tempObj[firstLetter]) {
                tempObj[firstLetter].push(item)
            } else {
                tempObj[firstLetter] = [item]
            }
        })
        // 处理右边索引数据
        const tempKeys = Object.keys(tempObj).sort()
        // 处理热门城市
        const res2 = await this.axios.get("area/hot")
        tempKeys.unshift("hot")
        console.log(res2, "res2Hot");
        tempObj["hot"] = res2.data.body
        // 处理定位城市
        const currentCity = await getCurrentCity()
        tempKeys.unshift("#")
        tempObj["#"] = [currentCity]
        this.setState({
            cityObj: tempObj,
            cityIndexList: tempKeys
        })
    }
    /**
     * 计算每一行的高度
     * TITLE_HEIGHT标题高度
     * CITY_HEIGHT 城市高度
     */
    calcRowHeight = ({ index }) => {
        const letter = this.state.cityIndexList[index]
        const list = this.state.cityObj[letter]
        return TITLE_HEIGHT + list.length * CITY_HEIGHT
    }
    // 格式化标题
    formatTitle = (letter) => {
        switch (letter) {
            case "#":
                return "定位城市"
            case "hot":
                return "热门城市"
            default:
                return letter.toUpperCase()
        }
    }
    // 选择城市
    toggleSelectCity = ({ value, label }) => {
        console.log({value,label})
        /* if (!['北京', '上海', '深圳', '广州'].includes(label)) {
            Toast.info("该城市暂无房源哦!")
            return
        } */
        setLocalCity({value,label})
        this.props.history.goBack()
    }
    // 渲染左边列表的每一样
    rowRenderer = ({
        index, // Index of row
        isScrolling, // The List is currently being scrolled
        isVisible, // This row is visible within the List (eg it is not an overscanned row)
        key, // Unique key within array of rendered rows
        parent, // Reference to the parent List (instance)
        style, // Style object to be applied to row (to position it);
        // This must be passed through to the rendered row element.
    }) => {
        const letter = this.state.cityIndexList[index]

        // If row content is complex, consider rendering a light-weight placeholder while scrolling.
        const list = this.state.cityObj[letter]

        // Style is required since it specifies how the row is to be sized and positioned.
        // React Virtualized depends on this sizing/positioning for proper scrolling behavior.
        // By default, the List component provides following style properties:
        //    position
        //    left
        //    top
        //    height
        //    width
        // You can add additional class names or style properties as you would like.
        // Key is also required by React to more efficiently manage the array of rows.
        console.log(list, "list-------------")
        console.log(letter, "letter--------")
        return (
            <div className={styles.city} key={key} style={style}>
                <div className={styles.title}>{this.formatTitle(letter)}</div>
                <div>
                    {list.map((item) => {
                        return (
                            <div key={item.value} className={styles.name} onClick={() => {
                                this.toggleSelectCity(item)
                            }}>
                                {item.label}
                            </div>
                        );
                    })}
                </div>
            </div>
        );
    }
    // 切换选择
    toggleSelect = (index) => {
        this.setState({
            selectIndex: index
        })
        this.listRef.current.scrollToRow(index);
    };
    // 该方法可以获取到滚动的位置信息
    onRowsRendered = ({ startIndex }) => {
        this.setState({
            selectIndex: startIndex,
        });
    };
    // 渲染右边的索引
    renderCityIndex = () => {
        const { cityIndexList, selectIndex } = this.state;
        let viewPortHeight = (this.getViewPortHeight() - 45) + "px"
        return (
            <div className={styles.cityIndex} style={{ height: viewPortHeight }}>
                {cityIndexList.map((item, index) => {
                    return (
                        <div
                            onClick={() => this.toggleSelect(index)}
                            className={styles.cityIndexItem}
                            key={item}
                        >
                            <span className={index === selectIndex ? styles.indexActive : ""}>
                                {item === "hot" ? "热" : item.toUpperCase()}
                            </span>
                        </div>
                    );
                })}
            </div>
        );
    };
    // 获取浏览器窗口可视区域高度
    getViewPortHeight = () => {
        return document.documentElement.clientHeight || document.body.clientHeight;
    }
    render() {
        const { cityObj, cityIndexList, selectIndex } = this.state
        return (
            <div className={styles.citylist} >
                <MyNavBar title="城市选择" />
                {cityObj &&
                    (<AutoSizer>
                        {({ height, width }) => (
                            <List
                                ref={this.listRef}
                                width={width}
                                height={height - 45}
                                rowCount={cityIndexList.length}
                                rowHeight={this.calcRowHeight}
                                rowRenderer={this.rowRenderer}
                                onRowsRendered={this.onRowsRendered}
                                scrollToAlignment="start"
                                scrollToIndex={selectIndex}
                            />
                        )}
                    </AutoSizer>)}
                {cityIndexList && this.renderCityIndex()}
            </div>
        );
    }
}

export default City;